import { isLoginPath, isSessionExpiredPath, LOGIN_PATH } from '@/utils/utils';
import type { MenuDataItem, Settings as LayoutSettings } from '@ant-design/pro-components';
import queryString from 'query-string';
import { history, RunTimeLayoutConfig, SelectLang } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { requestConfig } from '@/request';
import PageLoading from '@/components/PageLoading';
import React, { useEffect, useState } from 'react';
import { AvatarProps, message, Dropdown, Result } from 'antd';
import { AvatarName, AvatarDropdown } from '@/components/RightContent/AvatarDropdown';
import { ProLayoutProps } from '@ant-design/pro-components';
import type { MenuProps } from 'antd';
import screenfull from 'screenfull';
import { Provider } from 'react-redux';
import store from './pages/store/store';
import { getUserInfo } from './services/user';
import { getLock, getOpenStatus, setLock, setOpenStatus } from './utils/token';
import useWebSocket from './hooks/UseWebsocket';
import { useIntl } from '@umijs/max';
// import yue from './pages/images/yuelang.png';
import { useDetermineCardType } from './hooks/DetermineCardType';
import { ErrorBoun } from './components/DerivedStateFromError';
/**
 * 跳转登录页面
 */
const goLogin = () => {
  const query = queryString.parse(history.location.search);
  const { redirect_uri } = query as { redirect_uri: string };
  history.replace({
    pathname: LOGIN_PATH,
    search:
      redirect_uri &&
      queryString.stringify({
        redirect_uri: redirect_uri,
      }),
  });
};

/**
 * 获取当前用户信息
 */
const fetchUserInfo = async (): Promise<any> => {
  const res: any = await getUserInfo();

  if (res.code !== 0) return;
  const data = {
    accountId: res.data.id,
    username: res.data.username,
    avatar: res.data.avatar
      ? res.data.avatar
      : '',
    email: res.data.email,
    access: res.data.permission,
  };
  localStorage.setItem('userInfo', JSON.stringify(res.data));
  //
  return data;
};

export async function getInitialState(): Promise<{
  fetchUserInfo: () => Promise<API.CurrentUser | undefined>;
  settings: Partial<LayoutSettings>;
  currentUser: API.CurrentUser | undefined;
}> {
  /**
   * 控制台打印
   */

  return {
    fetchUserInfo,
    currentUser: isLoginPath() ? undefined : await fetchUserInfo(),
    settings: {
      ...defaultSettings,
    } as Partial<LayoutSettings>,
  };
}

// 锁屏icon
const LockScreen = () => {
  const lock = () => {
    history.replace({ pathname: '/lock' });
    setLock(true);
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center' }} onClick={lock}>
      <svg
        t="1699946626783"
        className="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="5177"
        width="15"
        height="15"
      >
        <path
          d="M817.131268 1023.996625H207.535906c-22.911829 0.203933-44.681635-8.840479-61.465289-25.35902C127.839041 980.691535 117.285529 955.199958 117.091793 928.678522V462.478376c0.203933-26.511239 10.788035-52.002816 29.01961-69.908099 16.783654-16.498148 38.512674-25.491576 61.444896-25.308037h482.392396v0.050983h126.438219c23.013795-0.203933 44.773405 8.830282 61.567255 25.38961 18.211182 17.94607 28.754498 43.437646 28.927841 69.948886v466.108376c-0.193736 26.511239-10.747249 52.002816-28.958431 69.897903-16.640901 16.355395-38.216971 25.338627-60.792311 25.338627z m-609.860475-63.402649h609.860475a23.329891 23.329891 0 0 0 16.314609-7.137641c6.281124-6.179158 9.931518-15.294946 10.023287-25.053122V462.855651c-0.06118-9.595029-3.711574-18.782194-10.023287-24.991941a23.391071 23.391071 0 0 0-16.385986-7.137641H206.903715a23.340087 23.340087 0 0 0-16.314609 7.137641c-6.291321 6.179158-9.951911 15.294946-10.053878 25.063318V928.32164c0.09177 9.768372 3.75236 18.924946 10.053878 25.124498a23.45225 23.45225 0 0 0 16.396182 7.137641h0.326292z"
          p-id="5178"
        ></path>
        <path
          d="M757.817468 394.232328h-63.402649v-149.89047c0-99.74344-81.134589-180.888226-180.87803-180.888226s-180.87803 81.114196-180.87803 180.857636v149.89047h-63.402648v-149.89047c0-134.69749 109.583189-244.311268 244.280678-244.311268s244.280679 109.613779 244.280679 244.311268z"
          p-id="5179"
        ></path>
        <path
          d="M511.303727 637.391377m-80.063943 0a80.063943 80.063943 0 1 0 160.127886 0 80.063943 80.063943 0 1 0-160.127886 0Z"
          p-id="5180"
        ></path>
        <path
          d="M471.01684 697.561694h78.0756v100.508187a18.833177 18.833177 0 0 1-18.833177 18.833177h-40.409247a18.833177 18.833177 0 0 1-18.833176-18.833177v-100.508187z"
          p-id="5181"
        ></path>
      </svg>
    </div>
  );
};

const WAlanguage = () => {
  const [isFullscreen, setIsFullscreen] = useState(false);
  const toggleFullscreen = () => {
    if (isFullscreen) {
      screenfull.exit();
    } else {
      screenfull.request();
    }
    setIsFullscreen(!isFullscreen);
  };

  return (
    <div
      className="fullscreen"
      onClick={() => {
        // setIsFullscreen(!isFullscreen);
      }}
    >
      <svg
        t="1747473193467"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="6366"
        width="15"
        height="15"
      >
        <path
          d="M832 744H638.4l-48 131.2h-57.6l166.4-440h75.2l166.4 440H880L832 744z m-17.6-51.2L740.8 488h-8L656 692.8h158.4zM532.8 697.6s-8-3.2-46.4-27.2c-44.8-27.2-86.4-52.8-121.6-83.2-35.2 28.8-75.2 56-121.6 81.6-46.4 25.6-100.8 49.6-163.2 73.6l-28.8-52.8c60.8-20.8 113.6-43.2 158.4-65.6 44.8-22.4 83.2-46.4 115.2-73.6-35.2-35.2-64-75.2-88-120S192 336 177.6 280h-104v-49.6h264c-12.8-40-22.4-72-30.4-92.8L360 128c3.2 6.4 6.4 19.2 12.8 35.2 4.8 16 9.6 30.4 12.8 40 1.6 6.4 4.8 16 9.6 28.8h249.6v49.6H537.6c-14.4 57.6-32 108.8-54.4 153.6-22.4 43.2-49.6 83.2-83.2 116.8 32 25.6 72 49.6 115.2 72 25.6 12.8 41.6 19.2 41.6 19.2l-24 54.4zM232 281.6c12.8 49.6 30.4 94.4 52.8 132.8 20.8 38.4 46.4 73.6 76.8 104 28.8-30.4 54.4-64 72-102.4 19.2-38.4 35.2-83.2 46.4-132.8H232z"
          p-id="6367"
        ></path>
      </svg>
    </div>
  );
};
// 全屏icon
const FullScreen = () => {
  const [TisFullscreen, TsetIsFullscreen] = useState(false);
  const toggleFullscreen = () => {
    if (TisFullscreen) {
      screenfull.exit();
    } else {
      screenfull.request();
    }
    TsetIsFullscreen(!TisFullscreen);
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center' }} onClick={toggleFullscreen}>
      <svg
        t="1699946550122"
        className="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="4153"
        width="15"
        height="15"
      >
        <path
          d="M240.8 196l178.4 178.4-45.6 45.6-177.6-179.2-68 68V128h180.8l-68 68z m133.6 408.8L196 783.2 128 715.2V896h180.8l-68-68 178.4-178.4-44.8-44.8zM715.2 128l68 68-178.4 178.4 45.6 45.6 178.4-178.4 68 68V128H715.2z m-65.6 476.8l-45.6 45.6 178.4 178.4-68 68H896V715.2l-68 68-178.4-178.4z"
          p-id="4154"
        ></path>
      </svg>
    </div>
  );
};
// 连接正常icon
const LinkNormal = () => {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <svg
        // eslint-disable-next-line react/no-unknown-property
        t="1699942267242"
        className="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        // eslint-disable-next-line react/no-unknown-property
        p-id="1837"
        width="20"
        height="20"
      >
        <path
          d="M900.816593 696.775111c19.64563 0 35.612444-15.890963 35.612444-35.422815v-99.745185H540.027259v99.745185c0 19.531852 15.928889 35.422815 35.612445 35.422815h325.176889z m35.536592-186.633481v-29.847704a35.574519 35.574519 0 0 0-35.574518-35.422815h-325.176889a35.574519 35.574519 0 0 0-35.574519 35.422815v29.847704h396.325926z m-448.360296 150.110814v-181.05837a87.04 87.04 0 0 1 87.153778-86.85037h97.166222V58.861037a25.78963 25.78963 0 0 0-25.865482-25.751704H113.398519a25.865481 25.865481 0 0 0-25.865482 25.78963v903.433481c0 14.260148 11.567407 25.78963 25.865482 25.78963h533.048888a25.903407 25.903407 0 0 0 25.865482-25.78963v-215.191703h-97.166222c-48.165926 0-87.22963-38.912-87.22963-86.888297v-0.037925z m-241.398519-203.662222c28.065185 1.365333 50.100148 24.424296 50.100149 52.375704s-22.034963 51.01037-50.062223 52.337778a52.527407 52.527407 0 0 1-52.565333-52.337778c0-28.823704 23.589926-52.337778 52.527407-52.337778z m54.082371-62.957037A174.610963 174.610963 0 0 1 352.407704 269.274074a175.597037 175.597037 0 0 1 124.965926-51.503407 25.675852 25.675852 0 1 1 0 51.579259 124.397037 124.397037 0 0 0-88.367408 36.446815 123.410963 123.410963 0 0 0-36.560592 87.988148 25.675852 25.675852 0 0 1-25.903408 25.637926 25.78963 25.78963 0 0 1-25.865481-25.751704z m83.626666 4.778667a97.507556 97.507556 0 0 1 97.545482-97.242074 25.827556 25.827556 0 0 1 0 51.541333 45.511111 45.511111 0 0 0-45.776593 45.662815 25.827556 25.827556 0 0 1-51.768889 0z"
          fill="#3372FC"
          // eslint-disable-next-line react/no-unknown-property
          p-id="1838"
        ></path>
      </svg>
    </div>
  );
};
// 连接异常icon
const LinkException = () => {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <svg
        t="1699942267242"
        className="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        // eslint-disable-next-line react/no-unknown-property
        p-id="1837"
        width="20"
        height="20"
      >
        <path
          d="M900.816593 696.775111c19.64563 0 35.612444-15.890963 35.612444-35.422815v-99.745185H540.027259v99.745185c0 19.531852 15.928889 35.422815 35.612445 35.422815h325.176889z m35.536592-186.633481v-29.847704a35.574519 35.574519 0 0 0-35.574518-35.422815h-325.176889a35.574519 35.574519 0 0 0-35.574519 35.422815v29.847704h396.325926z m-448.360296 150.110814v-181.05837a87.04 87.04 0 0 1 87.153778-86.85037h97.166222V58.861037a25.78963 25.78963 0 0 0-25.865482-25.751704H113.398519a25.865481 25.865481 0 0 0-25.865482 25.78963v903.433481c0 14.260148 11.567407 25.78963 25.865482 25.78963h533.048888a25.903407 25.903407 0 0 0 25.865482-25.78963v-215.191703h-97.166222c-48.165926 0-87.22963-38.912-87.22963-86.888297v-0.037925z m-241.398519-203.662222c28.065185 1.365333 50.100148 24.424296 50.100149 52.375704s-22.034963 51.01037-50.062223 52.337778a52.527407 52.527407 0 0 1-52.565333-52.337778c0-28.823704 23.589926-52.337778 52.527407-52.337778z m54.082371-62.957037A174.610963 174.610963 0 0 1 352.407704 269.274074a175.597037 175.597037 0 0 1 124.965926-51.503407 25.675852 25.675852 0 1 1 0 51.579259 124.397037 124.397037 0 0 0-88.367408 36.446815 123.410963 123.410963 0 0 0-36.560592 87.988148 25.675852 25.675852 0 0 1-25.903408 25.637926 25.78963 25.78963 0 0 1-25.865481-25.751704z m83.626666 4.778667a97.507556 97.507556 0 0 1 97.545482-97.242074 25.827556 25.827556 0 0 1 0 51.541333 45.511111 45.511111 0 0 0-45.776593 45.662815 25.827556 25.827556 0 0 1-51.768889 0z"
          fill="#d81e06"
          // eslint-disable-next-line react/no-unknown-property
          p-id="1838"
        ></path>
      </svg>
    </div>
  );
};
export const layout: RunTimeLayoutConfig = ({ initialState, loading }: any) => {
  const intl = useIntl();
  const [status, setStatus] = React.useState(false);
  const [Timer, setTimer] = useState('');
  const [Veson, setVeson] = useState('');
  const [clientid, setclientid] = useState('');

  const [openStatus, setOpen] = useState(false);
  useEffect(() => {
    let open = localStorage.getItem('status');
    if (open === 'true') {
      setOpen(true);
    } else {
      setOpen(false);
    }
  }, []);

  return {
    title: JSON.parse(localStorage.getItem('userInfo') || '').hotelName || '酒店',
    logo: JSON.parse(localStorage.getItem('userInfo') || '').logo,
    bgLayoutImgList: [
      {
        src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://img.alicdn.com/imgextra/i2/O1CN01O4etvp1DvpFLKfuWq_!!6000000000279-2-tps-609-606.png',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://img.alicdn.com/imgextra/i3/O1CN018NxReL1shX85Yz6Cx_!!6000000005798-2-tps-884-496.png',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    bgLayout: '#fff',
    token: {
      sider: {
        colorTextMenu: '#595959',
        colorMenuBackground: openStatus ? '#001529' : '#fff',
        colorTextMenuSelected: openStatus ? '#fff' : 'rgba(42,122,251,1)',
        colorTextMenuItemHover: openStatus ? '#fff' : 'rgba(42,122,251,1)',
        colorBgMenuItemSelected: openStatus ? '#1890ff' : '',
      },
      header: {
        colorBgHeader: '#fff',
      },
      pageContainer: {
        paddingBlockPageContainerContent: 12,
        paddingInlinePageContainerContent: 24,
      },
    },
    headerRender: (props: ProLayoutProps, defaultDom: React.ReactNode) => {
      return (
        <>
          {React.cloneElement(defaultDom as any, {
            style: {
              height: '70px',
              lineHeight: '50px',
            },
          })}
        </>
      );
    },
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      size: 'small',
      title: <AvatarName />,
      render: (props: AvatarProps, defaultDom: React.ReactNode) => {
        return (
          <AvatarDropdown
            setStatus={setStatus}
            setclientid={setclientid}
            setTimer={setTimer}
            setVeson={setVeson}
          >
            {defaultDom}
          </AvatarDropdown>
        );
      },
    },
    actionsRender: (props: ProLayoutProps) => {
      // const Time = updateTime();
      const items: MenuProps['items'] = [
        {
          key: '1',
          label: (
            <div style={{ padding: '5px' }}>
              <div>
                {intl.formatMessage({ id: 'app.client' })}ID: {clientid}
              </div>
              <div className="item">
                {intl.formatMessage({ id: 'app.Expiration time' })}: {Timer}
              </div>
              <div className="item">
                {' '}
                {intl.formatMessage({ id: 'app.Issuer version' })}: {Veson}
              </div>
            </div>
          ),
        },
      ];
      if (props.isMobile) return [];
      return [
        <>
          <>

          </>
        
          <LockScreen />
          <FullScreen />
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {status ? (
              <Dropdown menu={{ items }} placement="bottom">
                <a onClick={(e) => e.preventDefault()}>
                  <LinkNormal />
                </a>
              </Dropdown>
            ) : (
              <LinkException />
            )}
          </div>
        <SelectLang key="SelectLang" />
        </>,
      ];
    },
    disableContentMargin: false,
    waterMarkProps: {
      content: '',
    },
    childrenRender: (
      dom:
        | string
        | number
        | boolean
        | React.ReactElement<any, string | React.JSXElementConstructor<any>>
        | Iterable<React.ReactNode>
        | React.ReactPortal
        | null
        | undefined,
    ) => {
      if (loading) {
        return <PageLoading />;
      }
      return <Provider store={store}>{dom}</Provider>;
    },
    menuDataRender: (menuData: MenuDataItem[]) => {
      return menuData;
    },
    onPageChange: async () => {
      let isLock: boolean = false;

      if (getLock() === true) {
        isLock = true;
      }

      if (isLock === true) {
        message.warning(intl.formatMessage({ id: 'app.Please unlock it first' }));
        history.replace('/lock');
      }

      let gotoLogin: boolean = false;
      //任何一项没有数据没有数据
      if (!initialState || !initialState?.currentUser) {
        gotoLogin = true;
      }
      // 上述判断需要登录、路径为登录路径，会话过期路径不拦截
      // prettier-ignore
      if (gotoLogin && (isLoginPath() || isSessionExpiredPath())) {
        return;
      }
      //登录页面
      if (gotoLogin) {
        // 一般情况下，会先判断请求响应拦截器里的token存在或者token失效
        await message.error('请先登录', 0.1);
        goLogin();
        return;
      }
    },
    links: [],
    menuHeaderRender: undefined,
    ...initialState?.settings,
  };
};

/**
 * @name reuest 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...requestConfig,
};
